package com.gaoding.qa.auto.listener;


import com.gaoding.qa.auto.config.RuntimeContext;
import com.gaoding.qa.auto.data.TestJavaObject;
import com.gaoding.qa.auto.help.TestHelper;
import com.gaoding.qa.auto.interceptor.CoreInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author mobai
 * @since 2021/9/12 22:38
 */
@Slf4j
public class MyListener extends TestListenerAdapter {

    private static final ThreadLocal<TestJavaObject> CONTEXT=ThreadLocal.withInitial(TestJavaObject::new);


    private static final Map<String, AtomicInteger> counter=new ConcurrentHashMap<>();

    @Override
    public void onTestStart(ITestResult result) {
        Method method = result.getMethod().getConstructorOrMethod().getMethod();
        Class<?> declaringClass = method.getDeclaringClass();
        String key=declaringClass.getName()+"#"+method.getName();
        int currentCount=0;
        if (counter.containsKey(key)){
            currentCount = counter.get(key).incrementAndGet();
        }else{
            AtomicInteger atomicInteger=new AtomicInteger(currentCount);
            counter.put(key,atomicInteger);
        }
        TestJavaObject context=CoreInterceptor.MAP.get(key+"@"+currentCount);
        if (context==null){
            return;
        }
        CONTEXT.set(context);
        RuntimeContext runtimeContext = TestHelper.getContext();
        runtimeContext.setData(CONTEXT.get());
        runtimeContext.setExpectStatusCode(CONTEXT.get().getHttpStatus());

    }

    @Override
    public void onTestSuccess(ITestResult tr) {
        clearContext();
        TestHelper.clear();
        super.onTestSuccess(tr);
    }

    @Override
    public void onTestFailure(ITestResult tr) {
        clearContext();
        TestHelper.clear();
        super.onTestFailure(tr);
    }

    public static TestJavaObject getContext(){
        return CONTEXT.get();
    }

    public static void clearContext(){
        CONTEXT.remove();
    }
}
